using System.Collections.Concurrent;
using System.Linq;
using System.Threading.Tasks;

namespace Digitalmes.Events
{
    public class DeferrableEventArgs : EventArgs
    {
        private readonly ConcurrentBag<TaskCompletionSource<object>> taskCompletionSources = new ConcurrentBag<TaskCompletionSource<object>>();

        public Task DeferAsync()
        {
            return Task.WhenAll(taskCompletionSources.Select((tcs) => tcs.Task));
        }

        public Deferral GetDeferral()
        {
            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
            Deferral result = new Deferral(delegate
            {
                tcs.SetResult(null);
            });
            taskCompletionSources.Add(tcs);
            return result;
        }
    }
}